package com.yunao.service.template;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;

import com.yunao.commons.serachcore.core.bean.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MailTextStorage {

    @Autowired
    private MailTextTemplate template;

    public String store(String index, List<Article> articles) throws IOException {
        String mailText = template.process(articles);
        Path path = createIfExistDelete(index);
        Files.write(path, mailText.getBytes(), StandardOpenOption.CREATE);
        return path.toString();
    }

    private Path createIfExistDelete(String index) throws IOException {
        Path path = Paths.get("mailtext", index, "云奥舆情" + ".html");
        Files.deleteIfExists(path);
        if (Files.notExists(path.getParent().getParent())) {
            Files.createDirectories(path.getParent());
        } else if (Files.notExists(path.getParent())) {
            Files.createDirectory(path.getParent());
        }
        return Files.createFile(path);
    }

    public String getMailText(String key) throws IOException {
        return new String(Files.readAllBytes(Paths.get(key)));
    }

}
